<template>
	<div class="createPost-main-container">
		<el-row>
				<el-select :style="'width:'+ width+'px'" clearable v-model="region.provinceId" @change="areaChange(1)" placeholder="选择省">
					<el-option v-for="item in provinceList" :key="item.areaId" :label="item.name" :value="item.areaId">
					</el-option>
				</el-select>
				<el-select :style="'width:'+ width+'px'" clearable v-model="region.cityId" @change="areaChange(2)" placeholder="选择市">
					<el-option v-for="item in cityList" :key="item.areaId" :label="item.name" :value="item.areaId">
					</el-option>
				</el-select>
				<el-select :style="'width:'+ width+'px'" v-if="level == 3" clearable v-model="region.areaId" @change="areaChange(3)" placeholder="选择县/区">
					<el-option v-for="item in areaList" :key="item.areaId" :label="item.name" :value="item.areaId">
					</el-option>
				</el-select>
			</el-row>
	</div>
</template>
<script>
import request from '@/utils/request'
export default {
	props: ['region', 'width', 'level'],
  data() {
    return {
			provinceList: [],
			cityList: [],
			areaList: []
    }
	},
	watch: {
		'region.provinceId': function () {
			this.areaChange(1, false)
		},
		'region.cityId': function () {
			this.areaChange(2, false)
		}
	},
	mounted() {
		this.getProvinceList()
		// if (this.region.provinceId) {
		// 	this.areaChange(1, false)
		// }
		// if (this.region.cityId) {
		// 	this.areaChange(2, false)
		// }
	},
	methods: {
		getProvinceList() {
			request('areas/list').then(json => {
				this.provinceList = json.data.data
      }).catch((err) => {
        console.log(err)
      })
		},
		areaChange(val, isfre = true) {
			this.$emit('reseviced', this.region)
			if (val == 3) {
				return false
			}
			var value = val == 1 ? this.region.provinceId : this.region.cityId
			if (isfre) {
        this.areaList = []
				this.region.areaId = null
      }
			if (!value) {
				if (val == 1) {
					this.cityList = []
				}
        this.region.cityId = null
        return false
      }
      request('areas/list?parentId=' + value).then(json => {
        if (json.data.level == 2) {
					if (isfre) {
            this.region.cityId = null
          }
					this.cityList = json.data.data
        } else if (json.data.level == 3) {
					this.areaList = json.data.data
        }
      }).catch((err) => {
        console.log(err)
      })
    },
	}
}
</script>
<style scoped>

</style>
